﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.YouTube;
using Google.YouTube;

namespace YoutubeVideoManager
{
    /// <summary>
    /// Logica di interazione per PlaylistManager.xaml
    /// </summary>
    public partial class PlaylistManager : UserControl
    {
        public PlaylistManager()
        {
            InitializeComponent();

            VLC.VideoEnqueued += new EventHandler(VLC_VideoEnqueued);
            VLC.VideoDequeued += new EventHandler(VLC_VideoDequeued);
            VLC.PlaylistCleared += new EventHandler(VLC_PlaylistCleared);

            VLC.CurrentVideoChanged += new EventHandler(VLC_VideoChanged);
        }

        void VLC_PlaylistCleared(object sender, EventArgs e)
        {
            this.lvItems.Items.Clear();
        }

        void VLC_VideoDequeued(object sender, EventArgs e)
        {
            this.lvItems.Items.Remove((sender as Video).Title);
        }

        void VLC_VideoEnqueued(object sender, EventArgs e)
        {
            this.lvItems.Items.Add((sender as Video).Title);
        }
        
        void VLC_VideoChanged(object sender, EventArgs e)
        {
            Video v = sender as Video;
            
            WebClient client = new WebClient();
            byte[] buffer = client.DownloadData(new Uri(v.Thumbnails[0].Url));
            BitmapImage image = new BitmapImage();
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = ms;
                image.EndInit();
                image.Freeze();
                this.img.Source = image;
            }

            this.txtTitle.Text = v.Title;

            this.lvItems.SelectedItem = v.Title;
        }
    }
}
